'''-- token表
CREATE TABLE IF NOT EXISTS wx_token (
    token_id SERIAL PRIMARY KEY, -- token ID，唯一标识每个token
    user_id INT NOT NULL, -- token所属的用户ID
    token_type VARCHAR(50) NOT NULL, -- token类型，如：登录，分享，购买等
    token_content VARCHAR(100) NOT NULL, -- token内容，如：登录时生成的token字符串
    create_time TIMESTAMP DEFAULT now(), -- token生成时间
    expire_time TIMESTAMP NOT NULL -- token过期时间
);'''

import uuid
import datetime
import logging
import psycopg2


logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
class WxTokenTableMethods: 

    def __init__(self, conn, cur):
        self.cursor = cur
        self.conn = conn

    # 生成token
    def generate_token_content(self):
        token = str(uuid.uuid4())
        return token

    # 插入token
    def insert_token(self, user_id, token_type='login'):
        # 10年后过期
        expire_time = datetime.datetime.now() + datetime.timedelta(days=365*10)
        # 生成token
        token_content = self.generate_token_content()
        # 插入token

        sql = "INSERT INTO wx_token (user_id, token_type, token_content, expire_time) VALUES (%s, %s, %s, %s) RETURNING token_id"
        values = (user_id, token_type, token_content, expire_time)
        self.cursor.execute(sql, values)
        self.conn.commit()
        logger.info(f"insert token success token_id: {self.cursor.fetchone()['token_id']}")

        return token_content

    # 查询最近的token
    def query_latest_token_by_user_id(self, user_id, token_type='login'):
        sql = "SELECT token_id, token_content, expire_time FROM wx_token WHERE user_id = %s AND token_type = %s ORDER BY create_time DESC LIMIT 1"
        values = (user_id, token_type)
        self.cursor.execute(sql, values)
        result = self.cursor.fetchone()
        if result:
            logger.info(f"query latest token success token_id: {result['token_id']}")
            return result
        else:
            return None
        
    # 验证token 也是 查询token
    def verify_token(self, token_content, token_type='login'):
        # 查询token
        sql = "SELECT token_id, user_id, token_type, token_content, expire_time FROM wx_token WHERE token_content = %s AND token_type = %s"
        values = (token_content, token_type)
        self.cursor.execute(sql, values)
        result = self.cursor.fetchone()
        if result:
            # 验证token是否过期
            if result['expire_time'] > datetime.datetime.now():
                logger.info(f"verify token success token_id: {result['token_id']}")
                return result
            else:
                logger.info(f"verify token failed token_id: {result['token_id']} token expired")
                return None
        else:
            logger.info(f"verify token failed token_content: {token_content} not found")
            return None
        